package com.kgc.sbt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.kgc.sbt.api.CartApi;
import com.kgc.sbt.api.OrderApi;
import com.kgc.sbt.api.OrderInfoApi;
import com.kgc.sbt.config.annotation.RequestPermission;
import com.kgc.sbt.constant.SystemConstant;
import com.kgc.sbt.domain.Cart;
import com.kgc.sbt.domain.CartFrom;
import com.kgc.sbt.domain.Goods;
import com.kgc.sbt.domain.User;
import com.kgc.sbt.util.RedisUtils;
import com.kgc.sbt.util.RequestResult;
import com.kgc.sbt.util.ResultBuildUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * Created on 2021/6/22.
 * <p>
 * Author: a123
 * <p>
 * Description:
 */
@RestController
@Api(tags = "购物车操作入口，版本号:1.0.0")
@Slf4j
@RequestPermission
public class CartController {

    @Reference
    private CartApi cartApi;

    @Reference
    private OrderApi orderApi;

    @Reference
    private OrderInfoApi orderInfoApi;

    @Autowired
    private RedisUtils redisUtils;

    /**
     * @author: zzw
     * @date: 2021/6/22
     * @return
     * @description: 查询购物车详情
     */
    @GetMapping("/queryCart")
    @ApiOperation(value = "查询购物车详情",notes = "支持统一返回。。。")
    public RequestResult<List<CartFrom>> queryById(HttpServletRequest request){

        // 校验权限，是否已经登录
        String token = request.getHeader("token");

        // 校验token是否有效
        Integer userId = (Integer) redisUtils.get(token);;
        log.info("------ userId:" + userId);

        List<CartFrom> carts = cartApi.selectCartByUserId(userId);

        if (carts.isEmpty()){
            return ResultBuildUtil.fail("1005","该用户未添加任何商品");
        }

        return ResultBuildUtil.success(carts);
    }

    /**
     * @author: zzw
     * @date: 2021/6/22
     * @return
     * @description: 添加商品到购物车
     */
    @GetMapping("/addCart")
    @ApiOperation(value = "增加商品到购物车",notes = "支持统一返回")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId",required = true,value = "商品id"),
            @ApiImplicitParam(name = "number",required = true,value = "商品数量，必须大于0")
    })
    public RequestResult<String> insertCart(HttpServletRequest request,@RequestParam Integer goodsId,@RequestParam Integer number){

        // 校验权限，是否已经登录
        String token = request.getHeader("token");

        // 校验token是否有效
        Integer userId = (Integer) redisUtils.get(token);;
        log.info("------ userId:" + userId);

        // 查询用户信息
        User user = cartApi.selectUserById(userId);
        log.info("-----user:{}",user);

        // 查询商品信息
        Goods goods = cartApi.selectGoodsById(goodsId);
        log.info("-----goods:{}",goods);


        // 判断商品是否存在
        if(goods == null){
            return ResultBuildUtil.fail("1006","商品不存在");
        }

        // 判断是否存在用户
        if (user == null){
            return ResultBuildUtil.fail("1001","用户不存在");
        }

        // 添加数量是否小于0
        if(number <= 0){
            return ResultBuildUtil.fail("1002","商品数量不能小于0");

        }


        // 判断商品库存是否充足
        if (number > goods.getStock()){
            return ResultBuildUtil.fail("1004","库存不足，请减少购买数量");
        }

        // 增加商品时用户名与商品一致时，只增加数量
        if (cartApi.selectCartByUserIdAndGoodsId(userId,goodsId) != null){
            if (cartApi.updateCartNumberAdd(userId,goodsId,number)){
                return  ResultBuildUtil.success("添加同种商品成功");
            }
            return ResultBuildUtil.fail("1003","添加同种商品失败");
        }


        // 加入商品
        if (cartApi.insertCart(userId,goodsId,number)){

            return ResultBuildUtil.success("添加商品成功");
        }

        return ResultBuildUtil.fail("1005","添加商品失败");
    }

    /**
     * @author: zzw
     * @date: 2021/6/22
     * @return
     * @description: 购物车结算
     */
    @GetMapping("/totalFeel")
    @ApiOperation(value = "购物车结算",notes = "支持统一返回")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "addressId",required = true,value = "地址信息"),
            @ApiImplicitParam(name = "couponId",required = true,value = "优惠券信息")
    })
    public RequestResult<String> totalFeel(@RequestParam Integer[] cartIds,@RequestParam Integer addressId,@RequestParam Integer couponId){

        List<Cart> cartList = cartApi.selectCartByIds(cartIds);
        log.info("------ cartList={}",cartList);
        Integer[] goodsIds = new Integer[cartList.size()];
        Integer[] goodsNum = new Integer[cartList.size()];
        for (int i = 0;i < cartList.size(); i++){
            goodsIds[i] = cartList.get(i).getGoodsId();
            goodsNum[i] = cartList.get(i).getNumber();
        }
        log.info("------ goodsIds={}", Arrays.asList(goodsIds));
        log.info("------ goodsNum={}",Arrays.asList(goodsNum));

        // 用户id
        Integer userId = cartList.get(0).getUserId();
        log.info("------ userId={}",userId);

        // 模拟生成订单，封装订单会提参数省略
        String tradeOrderNo = "T" + DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now()) + UUID.randomUUID().toString().replace("-", "").substring(0,5);

        // 生成订单
        RequestResult<String> requestResult = orderApi.createOrder(userId, addressId, couponId, goodsIds, goodsNum,tradeOrderNo,null);

        // 生成订单
        if (requestResult.getCode().equals(SystemConstant.SYS_RESP_SUCCESS_CODE)){
            // 删除购物车
            if (cartApi.delCartByIds(cartIds)){
                // 购物车删除成功
                return ResultBuildUtil.success("生成订单成功，购物车数据删除成功，订单号为：" + tradeOrderNo + ",价格：" + orderInfoApi.getOrderInfoByOrderNumber(tradeOrderNo).getPayAmount());
            }else {

                return ResultBuildUtil.fail(SystemConstant.SYS_RESP_FAIL_CODE, "订单生成成功，购物车删除失败");
            }
        }else {
            return requestResult;
        }
    }

    /**
     * @author: zzw
     * @date: 2021/6/28
     * @return
     * @description: 删除购物车信息
     */
    @GetMapping("/delCart")
    @ApiOperation(value = "删除购物车",notes = "支持统一返回")
    public RequestResult<String> delCart(@RequestParam Integer[] cart){

        if (cartApi.delCartByIds(cart)){
            return ResultBuildUtil.success("删除购物车成功");
        }

        return ResultBuildUtil.fail("1005","删除购物车失败");
    }

    /**
     * @author: zzw
     * @date: 2021/6/28
     * @return
     * @description: 修改购物车商品的数量
     */
    @GetMapping("/updateCartNumber")
    @ApiOperation(value = "修改购物车商品数量",notes = "支持统一返回")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "goodsId",required = true,value = "商品id"),
            @ApiImplicitParam(name = "numberAdd",value = "增加商品数量",required = false),
            @ApiImplicitParam(name = "numberDel",value = "减少商品数量",required = false)
    })
    public RequestResult<String> updateCartNumber(HttpServletRequest request, @RequestParam Integer goodsId, @RequestParam(required = false) Integer numberAdd, @RequestParam(required = false) Integer numberDel){

        // 校验权限，是否已经登录
        String token = request.getHeader("token");

        // 校验token是否有效
        Integer userId = (Integer) redisUtils.get(token);;
        log.info("------ userId:" + userId);

        // 查询商品信息
        Goods goods = cartApi.selectGoodsById(goodsId);

        // 查询购物车商品信息
        Cart cart = cartApi.selectCartByUserIdAndGoodsId(userId,goodsId);

        if (numberAdd != null && numberDel != null){
            return ResultBuildUtil.fail("1009","无法同时增加或者减少商品数量");
        }else if (numberAdd != null && numberDel == null){
            if (cart.getNumber() + numberAdd > goods.getStock()){
                return ResultBuildUtil.fail("1008","库存不足");
            }else {
                if (cartApi.updateCartNumberAdd(userId,goodsId,numberAdd)){
                    return ResultBuildUtil.success("增加商品数量成功");
                }else {
                    return ResultBuildUtil.fail("1009","增加商品数量失败");
                }
            }
        }else if(numberDel != null && numberAdd == null){
            if (cart.getNumber() < numberDel){
                return ResultBuildUtil.fail("1007","购物车内的商品数量不足");
            }else {
                if(cartApi.updateCartNumberDel(userId,goodsId,numberDel)){
                    return ResultBuildUtil.success("减少商品数量成功");
                }else {
                    return ResultBuildUtil.fail("1009","增加商品数量失败");
                }
            }
        }else {
            return ResultBuildUtil.fail("1006","没有任何更改");
        }
    }
}
